package com.rzico.sbl.ui.report

import android.graphics.Point
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportGoodsBinding
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.ReportCarData
import com.rzico.sbl.model.ReportGoodsData
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToBuy
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.rzico.sbl.view.BeizerTextView
import com.rzico.sbl.viewmodel.ReportViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.listener._TextWatcher
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject
import kotlin.text.orEmpty

class ReportPromoteActivity : BaseActivity(R.layout.activity_report_goods) {

    private val mBinding by lazy { ActivityReportGoodsBinding.bind(getRootView()) }

    private val mKindList = ArrayList<CommonData>()
    private val mCarList = ArrayList<ReportCarData>()
    private var mKindId = ""
    private var mKeyWord = ""
    private var mOrderSn = ""

    override fun getViewModel() = get<ReportViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mOrderSn = intent.getExtra("orderSn")
            .apply {
                if (isNotEmpty()) {
                    mCarList.addItems(intent.getParcelableArrayListExtra("data"))
                    mBinding.goodsNum.setBadgeCount(mCarList.size)
                } else hasBuyOrder()
            }

        getKindData()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关商品信息！"
            }

            recycleList.also { layout ->
                layout.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<ReportGoodsData>(R.layout.item_report_promote) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_promote_name, bean.name)
                            text(R.id.item_promote_hint, "活动：${bean.phStock}")
                            text(R.id.item_promote_price, bean.phPrice.formatDecimal())

                            with<ImageView>(R.id.item_promote_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<EditText>(R.id.item_promote_input) {
                                if (it.tag != null && it.tag is TextWatcher) {
                                    it.removeTextChangedListener(it.tag as TextWatcher)
                                }

                                it.setText(bean.input)
                                it.setSelection(it.text.length)

                                val textWatcher = object : _TextWatcher() {
                                    override fun afterTextChanged(s: Editable) {
                                        bean.input = s.toString()
                                    }
                                }
                                it.addTextChangedListener(textWatcher)
                                it.tag = textWatcher
                            }

                            clicked(R.id.item_promote_add) { view ->
                                when {
                                    !bean.phMarketable -> {
                                        showToast("该商品已下架，请选择其他商品")
                                        return@clicked
                                    }

                                    bean.input.isEmpty() -> {
                                        showToast("请输入商品数量")
                                        return@clicked
                                    }
                                }

                                when (bean.input.intValue) {
                                    0 -> mCarList.removeAll { it.id == bean.id }
                                    else -> {
                                        if (mCarList.any { it.id == bean.id }) {
                                            mCarList
                                                .first { it.id == bean.id }
                                                .input = bean.input
                                        } else {
                                            mCarList.add(
                                                0,
                                                ReportCarData().apply {
                                                    id = bean.id
                                                    name = bean.name
                                                    thumbnail = bean.thumbnail
                                                    phPrice = bean.phPrice.orEmpty()
                                                    phStock = bean.phStock.orEmpty()
                                                    input = bean.input
                                                }
                                            )
                                        }
                                    }
                                }

                                // 购物动画
                                val position = IntArray(2)
                                view.getLocationInWindow(position)
                                animeCar(position[0], position[1], mCarList.size)
                            }
                        }
                    }
                    .attachTo(layout)
            }
        }
    }

    private fun initTabLayout() {
        mBinding
            .goodsTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mKindId = mKindList[it.position].id

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                mKindList.forEachIndexed { index, bean ->
                    addTab(newTab().setText(bean.name), index == 0)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .goodsSearch
            .apply {
                searchEdit.hint = "请输入关键字"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入关键字")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入关键字")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            goodsClear.oneClick {
                mCarList.notEmpty {
                    showHintDialog(
                        hint = "确定要清空购物车吗？",
                        onSure = {
                            mList.onEach {
                                it as ReportGoodsData
                                it.input = ""
                            }
                            mAdapter.notifyDataSetChanged()

                            mCarList.clear()
                            goodsNum.setBadgeCount(0)
                        }
                    )
                }
            }

            goodsLook.oneClick {
                startActivityEx<ReportCar2Activity>(
                    "orderSn" to mOrderSn,
                    "data" to mCarList
                )
            }

            observe<String>("carList2") { ids ->
                // 订单提交成功
                if (ids.startsWith("done")) {
                    ids.replace("done,", "")
                        .split(",")
                        .forEach { id ->
                            mCarList.removeAll { it.id == id }
                        }

                    goodsNum.setBadgeCount(mCarList.size)

                    updateList()

                    // 购物车删除商品
                } else {
                    ids.split(",")
                        .forEach { id ->
                            val item = mList.find { (it as ReportGoodsData).id == id }
                            item?.let {
                                it as ReportGoodsData
                                it.input = ""
                            }

                            mCarList.removeAll { it.id == id }
                        }

                    mAdapter.notifyDataSetChanged()
                    goodsNum.setBadgeCount(mCarList.size)
                }
            }
        }
    }

    /**
     * 添加购物车动画
     */
    private fun animeCar(x: Int, y: Int, count: Int) {
        val endPosition = IntArray(2)
        mBinding.goodsNum.getLocationInWindow(endPosition)

        (window.decorView as ViewGroup)
            .addView(
                BeizerTextView(baseContext).apply {
                    setStartPosition(Point(x, y))

                    setEndPosition(
                        Point(
                            endPosition[0],
                            endPosition[1]
                        )
                    )

                    startBeizerAnimation(
                        onFinished = {
                            mBinding.goodsNum.setBadgeCount(count)
                        }
                    )
                }
            )
    }

    private fun showOrderDialog() {
        showHintDialog(
            title = "温馨提示",
            hint = getString(R.string.hint_rbuy),
            cancel = "直接下单",
            sure = "去修改",
            isForced = true,
            onSure = { goToBuy() }
        )
    }

    /**
     * 判断是否有可修改采购单
     */
    private fun hasBuyOrder() {
        getViewModel()
            .requestBind(
                isLoading = false,
                requestUrl = ReportUrl.getBaseUrl().reportCut,
                params = arrayOf("type" to "0")
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    JSONObject(it).apply {
                        if (optNotNull("unprinted").intValue > 0) showOrderDialog()
                    }
                }
            )
    }

    /**
     * 商品分类
     */
    private fun getKindData() {
        getViewModel()
            .run {
                if (mOrderSn.isEmpty()) productCat()
                else productMCat(mOrderSn)
            }
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { list ->
                    mKindList.add(
                        CommonData().apply {
                            id = ""
                            name = "全部"
                        }
                    )
                    mKindList.addItems(list.filter { it.name == "桶装水" || it.name == "瓶装水" })

                    initTabLayout()
                }
            )
    }

    /**
     * 报货活动区列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .promoteList(
                page = index,
                orderSn = mOrderSn,
                kindId = mKindId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mList.forEach {
                        it as ReportGoodsData

                        it.promotions
                            .notEmpty {
                                it.phStock = this[0].introduction
                            }
                    }

                    mCarList.notEmpty {
                        forEach { bean ->
                            if (mList.any {
                                    (it as ReportGoodsData).id == bean.id
                                }) {
                                mList.find {
                                    (it as ReportGoodsData).id == bean.id
                                }.also {
                                    it as ReportGoodsData
                                    it.input = bean.input
                                    bean.phStock = it.phStock.orEmpty()
                                }
                            }
                        }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}